//<%@ page pageEncoding="UTF-8"%>
/////////////////常用功能///////////////////////////
//业务常量

var _LOGIN_KEY = '_user_';
var URL_LOGIN_PAGE = URL_ROOT+'/authority/login.html';
var URL_LOGIN_JSON = URL_ROOT+'/passport/login.json';
var URL_LOGOUT_JSON = URL_ROOT+'/passport/logout.json';

//@Override 重载
function ajaxRequest(url, params, callback){
	var interceptor = function(success, result){
		if(!success){
			alert('网络请求错误！');
		}else if(result.code=='0000'){
			
			var data = result.data;
			if(data){
				if(data['#']=='L'){
					data = Js.json2list(data);
				}else if(data.list && data.list['#']=='L'){
					data.list = Js.json2list(data.list);
				}
				result.data = data;
			}
			
			callback(result);
		}else if(result.code=='403'){
			location.href = URL_LOGIN_PAGE+'?from='+location.href;
			//Dialog.load(URL_LOGIN_PAGE, '登录', 500);
		}else{
			alert(result.message);
		}
	}
	sendJsonRequest(url, params, interceptor);
}

//@Override 重载
function sendJsonRequest(url, params, callback, method, cache){
	var jsonCallback = function(success, responseText){
		var jsObj = eval("("+responseText+")");
		callback(success, jsObj);
	}
	Ajax.sendHttpRequest(url, params, jsonCallback, method, cache);
}

//弹层
function unpopup(){
	Dialog.close();
}

function popup(element, title, width){
	Dialog.open(element, title, width);
}

var _cf = window.confirm;

window.confirm = function(msg, fun){
	msg = msg.replace('<b style="color:red">', ' [ ');
	msg = msg.replace('</b>', ' ] ');
	var r = _cf(msg)
	if (r){
		fun();
	}
}

//////////////////兼容////////////////
function uploadCallback(result){
	UploadFileUtil.uploadCallback(result);
}
/////////////////////////////////////////////////////

var AppUtil = {};

AppUtil.isLogin = function(){
	var cookieVal = Browser.getCookie(_LOGIN_KEY);
	return cookieVal;
}

AppUtil.login = function(){
	var values = FormUtil.getFormJson('loginForm');
	ajaxRequest(URL_LOGIN_JSON, values, function(result){
		var loginResult = result.data;
		if(loginResult.ok){
			var from = $E('from').value;
			if(from){
				location.href = from;
			}else{
				alert('登录成功！');
				location.reload();
			}
		}else if(loginResult.captcha){
			refreshCaptcha();
		}
		
		if(loginResult.msg){
			alert(loginResult.msg);
		}
	});
}

AppUtil.onLoginEnter = function(e){
	if(!e)e = window.event;
	var src = e.target||e.srcElement;
	
	if(src.tagName != 'INPUT'){
		return;
	}
	
	if(e.keyCode!=13){
		return;
	}
	
	AppUtil.login();
}

AppUtil.refreshCaptcha = function(img){
	var src = img.src;
	var url = StringUtil.parseUrl(src);
	var params = StringUtil.getUrlParamMap(url.query);
	params['_'] = new Date().getTime();
	img.src = (url.path + '?' + StringUtil.getUrlParamStr(params));
}

AppUtil.logout = function(){
	ajaxRequest(URL_LOGOUT_JSON, {}, function(r){alert('退出成功！')});
}

AppUtil.setOnload = function(initAction){
	if(typeof(MooTools)!='undefined'){
		window.addEvent('domready',function(){
			initAction();
		});
	}else if(typeof(jQuery)!='undefined'){
		$(document).ready(function(){
			initAction();
		});
	}else{
		window.onload = function(){initAction();}
	}
}

//上传
var UploadFileUtil = {};

UploadFileUtil.getImgUrl = function(path, width, height){
	if(width && height){
		return URL_ROOT+"/file/image/"+width+"x"+height+path;
	}else{
		return URL_ROOT+"/file/image/orig"+path;	
	}
}

UploadFileUtil.getDownloadUrl = function(path){
	return URL_ROOT+"/file/download"+path;
}

UploadFileUtil.uploadCallback = function(result){
	if(!result){
		return;
	}
	Js.log('uploadCallback:'+result);
	if(result.success!='Y'){
		alert('上传失败！');
		return;
	}
	$E(result.inputId+'_upload').value = Js.json2str(result);
	UploadFileUtil.previewImg(result.inputId+'_thumb', result.path);
}

UploadFileUtil.editFile = function(path, input){
	if(typeof(input)=='string'){
		input = document.getElementById(input);
	}
	input.value = path||'';
	
	parent = input.parentNode;
	parent.style = 'width:200px;height:30px';
	
	var inputId = input.name||input.id;
	var up_input = DomUtil.newElement('input', {name:inputId+"_upload", id:inputId+"_upload" ,'type':'hidden'}, parent);
	var iframe = DomUtil.newElement('iframe', {height:"100%",frameborder:"0",width:"100%",scrolling:"no",name:"uploadFrame",src:URL_ROOT+"/file/upfile.xhtml?inputId="+inputId}, parent);
}

UploadFileUtil.editFile2 = function(inputId, parent, path){
	parent.innerHTML = '';
	parent.style = 'width:200px;height:30px';

	var img = DomUtil.newElement('img', {id:inputId+"_thumb"}, parent);
	UploadFileUtil.previewImg(img, path);
	
	var up_input = DomUtil.newElement('input', {name:inputId+"_upload", id:inputId+"_upload" ,'type':'hidden'}, parent);
	var iframe = DomUtil.newElement('iframe', {height:"100%",frameborder:"0",width:"100%",scrolling:"no",name:"uploadFrame",src:URL_ROOT+"/file/upfile.xhtml?inputId="+inputId}, parent);
}

UploadFileUtil.viewFile = function(parent, path, width, height){
	var type = 'video';
	var extName = StringUtil.getExtName(path);
	if(extName=='jpg'||extName=='gif'||extName=='png'){
		type = 'img';
	}else if(extName=='mp3'){
		type = 'audio';
	}else{
		return '';
	}
	
	UploadFileUtil.viewMedia(parent, path, type, width, height);
}

//据说innerHTML效率高
UploadFileUtil.viewMedia = function(parent, path, type, width, height){
	if(typeof(parent)=='string'){
		parent = $E(parent);
	}
	var sHtml = '';
	if(type=='img'){
		var w = width||100;
		var h = height||100;
		var src = path ? URL_ROOT+'/file/image/'+w+'x'+h+path : '';
		sHtml = '<img src="'+src+'"></img';
	}else{
		var src = path ? URL_ROOT+'/file/download'+path:'';
		var tagName = type||'video';
		var size = '';
		if(width){
			size = ' width="'+width+'"';
		}
		if(height){
			size += ' height="'+height+'"';
		}
		sHtml = '<'+tagName + size + ' src="'+src+'" controls="controls"></'+tagName+'>';
	}
	parent.innerHTML = sHtml;
}

UploadFileUtil.previewImg = function(img, path, parent){
	var imgId = null;
	if(typeof(img)=='string'){
		imgId = img;
		img = $E(imgId);
	}
	
	if(parent){
		parent.innerHTML = '';
	}
	
	if(!img){
		var attrs = null;
		if(imgId){
			attrs = {id:imgId};
		}
		img = DomUtil.newElement('img', attrs, parent);
	}
	if(!img){
		return;
	}
	if(path){
		var reg = /^https?:\/\//;
		if(!reg.test(path)){
			var w = parseInt(img.style.maxWidth)||100;
			var h = parseInt(img.style.maxHeight)||100;
			if(path.charAt(0)!='/'){
				path = '/'+path;
			}
			path = URL_ROOT+'/file/image/'+w+'x'+h+path;
		}
		img.src = path;
		img.style.display = '';
	}else{
		img.src = '';
		img.style.display = 'none';
	}
}


var NavUtil = {};

NavUtil.backToList = function(url, exParam){
	var map = Browser.getUrlParamMap();
	delete map[exParam];
	var paramStr = StringUtil.getUrlParamStr(map);
	if(paramStr && paramStr.length>0){
		url += '?' + paramStr;
	}
	location.href = url;
};

NavUtil.makePageTabs = function(id, pageInfo, currentPageNo){
	var pageContainer = document.getElementById(id);
	pageContainer.setAttribute('class', 'page');
	DomUtil.removeChildren(pageContainer);
	
	if(!pageInfo){
		return pageContainer;
	}
	
	var ss = pageInfo.split(',');
	for(var i=0;i<ss.length;i++){
		var pageNo = ss[i];
		if(pageNo==-1){
			continue;
		}
		var tag;
		if(pageNo==0){
			tag = document.createElement('strong');
			tag.innerHTML = '...';
		}else{
			tag = document.createElement('a');
			tag.innerHTML = pageNo;
		}
		if(pageNo==(currentPageNo || 1)){
			tag.setAttribute('class', 'selected');
		}
		pageContainer.appendChild(tag);
	}
	return pageContainer;
}

function ModuleContext(name, label, contextPath){
	contextPath = contextPath||URL_ROOT;
	this.OBJ_NAME = name;
	this.OBJ_LABEL = label;
	this.OBJ_ID = 'id';
	this.EDIT_FORM_ID = this.OBJ_NAME+'EditForm';
	this.EDIT_PANEL_ID = this.OBJ_NAME+'EditPanel';
	this.URL_PREFIX = contextPath+'/'+StringUtil.getVariable(name);
	this.URL_PAGE_QUERY = this.URL_PREFIX+"/list.json";
	this.URL_GET = this.URL_PREFIX+"/get.json";
	this.URL_SAVE = this.URL_PREFIX+"/save.json"
	this.URL_DEL = this.URL_PREFIX+"/delete.json";
	this.URL_BATCH_DELETE = this.URL_PREFIX+"/batchDelete.json";
	this.URL_ENABLE = this.URL_PREFIX+"/enable.json";
}

function ModuleUI(ctx){
	
	var oThis = this;
	
	this.addXXX = function(){
		var title = '新建 '+ctx.OBJ_LABEL;
		var form = document.getElementById(ctx.EDIT_FORM_ID);
		FormUtil.clearForm(form);
		
		Dialog.open(ctx.EDIT_PANEL_ID, title, 450);
		oThis.setEditFiles();
	}
	
	this.editXXX = function(id){
		var title = (id?"编辑 ":"新建 ")+ctx.OBJ_LABEL;
		var form = document.getElementById(ctx.EDIT_FORM_ID);
		FormUtil.clearForm(form);
	
		var values = {"id":id};
		var onJsonLoad = function(result){
			Dialog.open(ctx.EDIT_PANEL_ID, title, 450);
			FormUtil.setFormJson(form, result.data);
			oThis.setEditFiles(result.data);
		};
		ajaxRequest(ctx.URL_GET, values, onJsonLoad);
	}
	
	this.setEditFiles = function(obj){
		Js.log('未实现!');
	}
	
	this.saveXXX = function(){
		var check = function(submitFun){
			if(!oThis.checkEditForm()){
				return;
			}
			submitFun();
		}
		var submitFun = function(){
			ajaxSubmit(ctx.URL_SAVE, ctx.EDIT_FORM_ID);
		};
		check(submitFun);
	}
	
	this.checkEditForm = function(){
		var vConf = {};
		//
	 	vConf = [
		{"name":"id","format":"Integer","tip":" 格式错误!"}
		, {"name":"albumId","format":"Integer","tip":"相册 格式错误!"}
		];	var v = new Validator(ctx.EDIT_FORM_ID, vConf, true);
		var ok = v.validate();
		if(!ok){
			return false;
		}
		return true;
	}
	
	this.deleteXXX = function(id){
		var del_submit = function(){
			var values = {"id":id};
			ajaxRequest(ctx.URL_DEL, values, function(result){
				location.reload();
			},false,true);
		}
		var msg = '您确定要删除吗？';
		var name = null;
		if(name){
			msg = '您确定要删除<b style="color:red">'+name+'</b>吗？'
		}
		confirm(msg, del_submit);
	}
	
	this.deleteSelectedXXX = function(){
		var idseq = FormUtil.getInputValue('checkbox');
		if(!idseq){
			alert('没有选中');
			return;
		}
		var del_submit = function(){
			var values = {"idseq":idseq};
			ajaxRequest(ctx.URL_BATCH_DELETE, values, function(result){
				location.reload();
			},false,true);
		}
		var msg = '您确定批量删除吗？';
		confirm(msg, del_submit);
	}
	
	this.enableXXX = function(id, input){
		var enabled = input.value;
		var fun_submit = function(){
			var values = {"id":id, "enabled":enabled};
			ajaxRequest(ctx.URL_ENABLE, values, function(result){
				location.reload();
			})
		}
		fun_submit();
	}
	
	this.makeViewList = function(objList, tplObj, append){
		var tplParent = tplObj.parentNode;
		//clean
		if(!append){
			DomUtil.removeChildren(tplParent, 1);
			tplParent.appendChild(tplObj);
		}
		//make
		var newObj;
		for(var i=0;i<objList.length;i++){
			newObj = tplObj.cloneNode(true);
			newObj.style.display='';
			tplParent.appendChild(newObj);
			oThis.setViewItem(objList[i], newObj);
		}
		tplObj.style.display='none';
	
		FormUtil.associateCheckBox('checkboxAll', 'checkbox');
	}
	
	this.setViewItem = function(dataObj, viewObj){
		viewObj.setAttribute('class','row');
		viewObj.setAttribute('id', 'XXXListItem_' + dataObj.id);
		var children = DomUtil.getChildren(viewObj);

		var i = 1;
		for(;i<children.length-2;i++){
			var name = DomUtil.getText(children[i]);
			children[i].innerHTML = Widget.getView(dataObj[name], 'text');
		}

		children[i].firstChild.onclick = function(){oThis.editXXX(dataObj.id);};
		children[i].firstChild.onclick = function(){oThis.deleteXXX(dataObj.id);};
	}
	
	//UI
	
	this.pageJump = function(e){
		if(!e)e = window.event;
		var src = e.target||e.srcElement;
		if(src.tagName != 'A'){
			return;
		}
		if(src.getAttribute('class') == 'selected'){
			return;
		}
		var pageNo = src.innerHTML;
		
		var params = Browser.getHashParamMap();
		params.pageNo = pageNo;
		this.pageQuery(ctx.URL_PAGE_QUERY, params);
	}
	
	this.pageQuery = function(url, params){
		var templateId = 'row_template';
		var tplObj = document.getElementById(templateId);
		if(!tplObj){
			return;
		}
		var pageNo = params.pageNo;
		ajaxRequest(url, params, function(result){
			var data = result.data;
			var datalist = data.list;
			var pageTags = data.pageTags;
			oThis.makeViewList(datalist, tplObj);
			var pageContainer = NavUtil.makePageTabs('page', pageTags, pageNo);
			pageContainer.onclick = function(e){oThis.pageJump(e);};
			if(params){
				delete params['_'];
				Browser.setHashParamMap(params);
			}
		});
	}
	
	this.searchForm = function(){
		this.pageQuery(ctx.URL_PAGE_QUERY, FormUtil.getFormJson('searchForm'));
		var searchForm = $E('searchForm');
		if(searchForm)searchForm.reset();
	}
	
	//onload事件
	this.initXXXAction = function(){
		EventUtil.addEvent(ctx.OBJ_NAME+'AddBtn', 'click', function(){oThis.addXXX();});
		EventUtil.addEvent(ctx.OBJ_NAME+'SaveBtn', 'click', function(){oThis.saveXXX();});
		EventUtil.addEvent(ctx.OBJ_NAME+'DelBtn', 'click', function(){oThis.deleteSelectedXXX();});
		EventUtil.addEvent('btn_search', 'click', function(){oThis.searchForm();});
		
		var params = Browser.getHashParamMap();
		oThis.pageQuery(ctx.URL_PAGE_QUERY, params);
	}
	
	AppUtil.setOnload(function(){oThis.initXXXAction();});
}

var _______________________________________;

function Page(pageSize, pageno, rowTotal){
    this.pageSize = pageSize||20;
    this.pageNo = pageno||1;
    this.rowTotal = rowTotal||0;
}

Page.prototype.getPageCount = function() {
	var pageCount =  Math.ceil(this.rowTotal/this.pageSize);
	return pageCount;
}

Page.prototype.getStartRow = function() {
	return this.pageSize * (this.pageNo - 1);
}

Page.prototype.getEndRow = function() {
	var rowEnd = this.getStartRow() + this.pageSize - 1;
	if(rowEnd>this.rowTotal){
		rowEnd = this.rowTotal;
	}
	return rowEnd;
}

/* OptionDialog */
function OptionDialog(optionUrl, valAttr, labelAttr, boxName){
	this.type = 'checkbox';//'checkbox'||'radio'
	this.boxName = boxName||('od_opt_' + new Date().getTime());
	this.optionUrl = (typeof(optionUrl)=='function')?optionUrl:function(){return optionUrl;};

	this.itemData = null;
	this.valAttr = valAttr||'id';
	this.labelAttr = labelAttr||'name';
	
	this.title = '请选择';
	this.width = 500;
	this.buttons = null;
	
	this.onOptionClick = null; 	//当点击选项时
	this.onOptionDbClick = null; //当双击选项时
	
	this.filter = false;
	this.page = null;
	
	this.view = null;
	this.form = null;
}

/**
 * 得到选中的项目的值
 */
OptionDialog.prototype.getSelectedValue = function(format){
	return FormUtil.getInputValue(this.boxName, this.form, format);
}

/**
 * 弹出对话框
 * 并根据value设置选中项
 */
OptionDialog.prototype.popup = function(value){
	var oThis = this;
	
	var newOptionUrl = this.optionUrl();
	if(newOptionUrl){
		var refresh = (this._lastOptionUrl != newOptionUrl);
		//加载数据
		if(!this.itemData || refresh){
			this.load(newOptionUrl, function(){
				oThis.popup(value);
			});
			return;
		}
	}

	//构造对话框
	
	if(this.view){
		this.view.parentNode.removeChild(this.view);
		this.view = null;
	}
	if(!this.view){
		this._createView();
	}
	
	//显示对话框
	Dialog.open(this.view, this.title, this.width, this.buttons);
	
	//设置value
	this.setValue(value);
}

OptionDialog.prototype.setValue = function(value){
	if(value){
		var inputArray = FormUtil.getInputArray(this.boxName, this.form);
		FormUtil.setInputArray(inputArray, value);
	}else{
		FormUtil.clearForm(this.form);
	}
}

OptionDialog.prototype.unpopup = function(value){
	Dialog.close();
	var view = this.view;
	window.setTimeout(function(){view.parentNode.removeChild(view);}, 1000);
	this.view = null;
}

OptionDialog.prototype.load = function(optionUrl, onOptionsLoad){
	var oThis = this;
	ajaxRequest(optionUrl, {}, function(result){
		oThis.itemData = result.data;
		oThis._lastOptionUrl = optionUrl;
		onOptionsLoad();
	});
}


OptionDialog.prototype._createView = function(){
	this.view = DomUtil.newElement('div', {tabindex:0}, document.body);
	var filterInput = null;
	var filterButton = null;
	var pageSelect = null;
	
	//create elements
	if(this.filter){
		var searchBarDiv = DomUtil.newElement('div', {'class':'od_searchbar'}, this.view);
		filterInput = DomUtil.newElement('input', {'class':'od_filter_keyword'}, searchBarDiv);
		filterButton = DomUtil.newElement('a', {'class':'od_filter_button'}, searchBarDiv);
		DomUtil.setText(filterButton, '搜索');
	}
	
	var dateaInfo = DomUtil.newElement('span', {'class':'od_data_info'}, searchBarDiv);
	
	var formDiv = DomUtil.newElement('div', {'class':'od_main_div'}, this.view);
	this.form = DomUtil.newElement('form', null, formDiv);

	if(this.page){
		var pageBar = DomUtil.newElement('div', {'class':'od_pagebar'}, this.view);
		DomUtil.appendText(pageBar, '分页');
		pageSelect = DomUtil.newElement('select', {'class':'od_pageSelect'}, pageBar);

	}
	
	//setup event
	var oThis = this;
	
	var reviewData = function(){
		
		var evt = arguments[0]||window.event;
		if(evt && evt.type=='keydown'){
			var key = evt.keyCode||evt.which;
			if(key != 13){
				return;
			}
			
		}
		
		if(filterInput){
			var keyword = filterInput?filterInput.value:null;
			
			if(evt && evt.type=='keydown' && oThis.type=='radio' && oThis._lastKeyword==keyword){
				var radioElement = oThis.form[oThis.boxName];
				if(radioElement && radioElement.length==undefined){
					if(!radioElement.checked){
						radioElement.checked = true;
						radioElement.parentNode.onclick();
					}else{
						radioElement.parentNode.ondblclick();
					}
				}
				return;
			}
			
			oThis._lastKeyword = keyword;
		}
		
		if(!oThis.itemData){
			alert('no data!');
			return;
		}
		
		var newlist = oThis.itemData;
		
		if(filterInput){
			var keyword = filterInput?filterInput.value:null;
			newlist = BeanUtil.findList(oThis.itemData, oThis.labelAttr, keyword);
		}

		dateaInfo.innerHTML = '共有['+newlist.length+']条数据';
		
		if(oThis.page){
			var page = oThis.page;
			var pageNo = pageSelect.value||1;
			page.pageNo = pageNo;
			page.rowTotal = newlist.length;
			
			newlist = newlist.slice(page.getStartRow(), page.getEndRow()+1);
			
			//pageTabs
			var pageCount = page.getPageCount();
			pageSelect.options.length = 0;
			for(var i=1; i<=pageCount; i++){
				var opt = new Option(i, i);
				if(pageNo==i){
					opt.selected = (i==pageNo);
				}
				pageSelect.options.add(opt);
			}
			
		}
		
		oThis._setOptItems(newlist);
	}
	
	if(filterButton){
		
		filterButton.onclick = filterInput.onkeydown = function(){
			reviewData(arguments[0]);
		};
		
		this.view.onkeydown = function(){
			filterInput.focus();
		};
	}
	
	if(pageSelect){
		pageSelect.onchange = reviewData;
	}

	reviewData();
}

OptionDialog.prototype._setOptItems = function(list){
	var oThis = this;
	
	this.form.innerHTML = '';
	for(var i=0;i<list.length;i++){
		var item = list[i];
		
		var labelText = getLabelText(item, this.labelAttr);
		var label = DomUtil.newElement('label', {'class':'od_form_item', 'title':labelText}, this.form);
		var input = DomUtil.newElement('input', {'type':this.type, 'name':this.boxName, 'value':item[this.valAttr]}, label);
		DomUtil.appendText(label, labelText);
		setOptionClick(label, item, input);
	}
	
	DomUtil.newElement('div', {'style':'clear:both'}, this.form);
	
	/////////////////////////////////
	function getLabelText(item, labelAttr){
		if(typeof(labelAttr)=='string'){
			return item[labelAttr];
		}
		var text = '';
		var ppArray = labelAttr;
		for(var j=0;j<ppArray.length;j++){
			var pp = ppArray[j];
			if(j>0){
				text += ' ';
			}
			text += item[pp];
		}
		return text;
	}

	function setOptionClick(obj, dataItem, box){
		obj.onclick = function(){
			if(oThis.onOptionClick!=null){
				oThis.onOptionClick(dataItem, box);
			}
		};
		
		obj.ondblclick = function(){
			if(oThis.onOptionDbClick!=null){
				oThis.onOptionDbClick(dataItem, box);	
			}
		};
	}
}

/* OptionDialog end */

/**
 * 得到选中的项目
 */
OptionDialog.prototype.getSelected = function(){
	var result = [];
	var inputs = FormUtil.getInputArray(this.boxName, this.form, 'checked', true);
	for(var i=0;i<inputs.length;i++){
		var input = inputs[i];
		var p = input.parentNode;
		var item = {};
		item.id = input.id;
		item.value = input.value;
		item.text = DomUtil.getText(p);
		result.push(item);
	}
	return (this.type=='radio'?result[0]:result);
}
